package com.empl.mgr.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.empl.mgr.constant.PageConstant;
import com.empl.mgr.dao.DepartmentDao;
import com.empl.mgr.dao.EmployeesBasicDao;
import com.empl.mgr.dao.PositionDao;
import com.empl.mgr.dao.SalaryDao;
import com.empl.mgr.dto.EmployeesInternshipListDto;
import com.empl.mgr.dto.SalaryInfoDto;
import com.empl.mgr.field.TeDepartmentField;
import com.empl.mgr.field.TePositionField;
import com.empl.mgr.field.TeSalaryField;
import com.empl.mgr.model.TeDepartment;
import com.empl.mgr.model.TeEmployeesBasic;
import com.empl.mgr.model.TePosition;
import com.empl.mgr.model.TeSalary;
import com.empl.mgr.service.SalaryService;
import com.empl.mgr.support.JSONReturn;
import com.empl.mgr.utils.CompareUtil;
import com.empl.mgr.utils.DateTimeUtil;
import com.empl.mgr.utils.PageUtils;
import com.empl.mgr.utils.PoiExcelExport;

@Scope
@Service
@Transactional(readOnly = true)
public class SalaryServiceImpl implements SalaryService {

	
	@Autowired
	private PositionDao positionDao;
	@Autowired
	private DepartmentDao departmentDao;
	@Autowired
	private EmployeesBasicDao employeesBasicDao;
	
	@Autowired
	private SalaryDao salaryDao;
	
	

	
	
	public JSONReturn findAllSalaryList(int type, String value, long dept, long position, int page, String salaryMonth, String acctName
			) {
		// TODO Auto-generated method stub
		List <EmployeesInternshipListDto> dtoList = null;
		dtoList = employeesBasicDao.findEmployeesList(type, value, dept, position, page);
		if (CollectionUtils.isEmpty(dtoList)){
			dtoList = employeesBasicDao.findEmployeesList(type, value, dept, position, page-1);
			if (CollectionUtils.isEmpty(dtoList)){
				return JSONReturn.buildFailure("未获取到相关数据!");
			}
			
		}
			
		
		if(salaryMonth == "NoSalaryMonth" || salaryMonth == ""){
			salaryMonth = DateTimeUtil.conversionTime(DateTimeUtil.getCurrentTime(), "yyyy-MM");
		}
		
		List <TeSalary> salaryList = salaryDao.findSalaryList(salaryMonth);
		
		List <SalaryInfoDto> salaryDtoList = new ArrayList<SalaryInfoDto>();
		
		TeDepartment department = null;
		TePosition post = null;
		
		for (EmployeesInternshipListDto dto : dtoList) {
			if (dto.getDeptId() > 0) {
				department = departmentDao.findUniqueByProperty(TeDepartmentField.DEPT_ID, dto.getDeptId());
				dto.setDepartment(CompareUtil.isNotEmpty(department) ? department.getDeptName() : null);
			}
			if (dto.getPositionId() > 0) {
				post = positionDao.findUniqueByProperty(TePositionField.PO_ID, dto.getPositionId());
				dto.setPosition(CompareUtil.isNotEmpty(post) ? post.getPoName() : null);
			}
			
			boolean flag = false;
			TeSalary teSalary = null;
			
			for(TeSalary salary : salaryList){
				if(dto.getId() == salary.getEmployeesId()){
					flag = true;
					teSalary = salary;
				}
				
			}
			
			if(flag){
				SalaryInfoDto salaryInfo = new SalaryInfoDto();
				salaryInfo.setId(teSalary.getSalaryId());
				salaryInfo.setEmployeesName(dto.getName());
				salaryInfo.setEmId(dto.getId());
				salaryInfo.setSex(dto.isSex());
				salaryInfo.setDeparemtn(department.getDeptName());
				
				salaryInfo.setBaseSalary(teSalary.getBaseSalary());
				salaryInfo.setLateSalary(teSalary.getLateSalary());
				salaryInfo.setAbsenceSalary(teSalary.getAbsenceSalary());
				salaryInfo.setWuxianyijin(teSalary.getWuxianyijin());
				salaryInfo.setOvertimeSalary(teSalary.getOvertimeSalary());
				salaryInfo.setBonusSalary(teSalary.getBonusSalary());
				salaryInfo.setSalaryTime(teSalary.getSalaryTime());
				salaryDtoList.add(salaryInfo);
			}else{
				SalaryInfoDto salaryInfo = new SalaryInfoDto();
				salaryInfo.setEmployeesName(dto.getName());
				salaryInfo.setEmId(dto.getId());
				salaryInfo.setSex(dto.isSex());
				salaryInfo.setDeparemtn(department.getDeptName());
				salaryDtoList.add(salaryInfo);
			}
		}
		return JSONReturn.buildSuccess(salaryDtoList);
	}
	
	public List<SalaryInfoDto> findAllSalaryListByTime(String salaryMonth) {
		// TODO Auto-generated method stub
		List <EmployeesInternshipListDto> dtoList = null;
		dtoList = employeesBasicDao.findEmployeesList();
		if (CollectionUtils.isEmpty(dtoList))
			return null;
		
		List <TeSalary> salaryList = salaryDao.findSalaryList(salaryMonth);
		
		List <SalaryInfoDto> salaryDtoList = new ArrayList<SalaryInfoDto>();
		
		TeDepartment department = null;
		TePosition post = null;
		
		for (EmployeesInternshipListDto dto : dtoList) {
			if (dto.getDeptId() > 0) {
				department = departmentDao.findUniqueByProperty(TeDepartmentField.DEPT_ID, dto.getDeptId());
				dto.setDepartment(CompareUtil.isNotEmpty(department) ? department.getDeptName() : null);
			}
			if (dto.getPositionId() > 0) {
				post = positionDao.findUniqueByProperty(TePositionField.PO_ID, dto.getPositionId());
				dto.setPosition(CompareUtil.isNotEmpty(post) ? post.getPoName() : null);
			}
			
			boolean flag = false;
			TeSalary teSalary = null;
			
			for(TeSalary salary : salaryList){
				if(dto.getId() == salary.getEmployeesId()){
					flag = true;
					teSalary = salary;
				}
				
			}
			
			if(flag){
				SalaryInfoDto salaryInfo = new SalaryInfoDto();
				salaryInfo.setId(teSalary.getSalaryId());
				salaryInfo.setEmployeesName(dto.getName());
				salaryInfo.setEmId(dto.getId());
				salaryInfo.setSex(dto.isSex());
				salaryInfo.setDeparemtn(department.getDeptName());
				
				salaryInfo.setBaseSalary(teSalary.getBaseSalary());
				salaryInfo.setLateSalary(teSalary.getLateSalary());
				salaryInfo.setAbsenceSalary(teSalary.getAbsenceSalary());
				salaryInfo.setWuxianyijin(teSalary.getWuxianyijin());
				salaryInfo.setOvertimeSalary(teSalary.getOvertimeSalary());
				salaryInfo.setBonusSalary(teSalary.getBonusSalary());
				salaryInfo.setSalaryTime(teSalary.getSalaryTime());
				salaryDtoList.add(salaryInfo);
			}else{
				SalaryInfoDto salaryInfo = new SalaryInfoDto();
				salaryInfo.setEmployeesName(dto.getName());
				salaryInfo.setEmId(dto.getId());
				salaryInfo.setSex(dto.isSex());
				salaryInfo.setDeparemtn(department.getDeptName());
				salaryDtoList.add(salaryInfo);
			}
		}
		return salaryDtoList;
	}
	
	
	public JSONReturn findSalaryPage(int type, String value, long dept, long position, int page, String acctName) {
		int count = salaryDao.findSalaryPage(type, value, dept, position);
		return JSONReturn.buildSuccess(PageUtils.calculatePage(page, count, PageConstant.PAGE_LIST));
	}

	@Transactional
	public JSONReturn addSalary(long emId, String baseSalary, String lateSalary, String absenceSalary, String wuxianyijin,
			String overtimeSalary, String bonusSalary, String acctName) {
		// TODO Auto-generated method stub
		if (StringUtils.isEmpty(baseSalary) || StringUtils.isEmpty(lateSalary) || StringUtils.isEmpty(absenceSalary) || StringUtils.isEmpty(wuxianyijin) || StringUtils.isEmpty(overtimeSalary) || StringUtils.isEmpty(bonusSalary))
			return JSONReturn.buildFailure("添加失败!");
		/*TeAccount account = accountDao.findUniqueByProperty(TeAccountField.ACCT_NAME, user);
		if (CompareUtil.isNotEmpty(account))
			return JSONReturn.buildFailure("添加失败, 用户名重复!");*/
		
		TeSalary teSalary = new TeSalary();
		teSalary.setBaseSalary(Double.parseDouble(baseSalary));
		teSalary.setLateSalary(Double.parseDouble(lateSalary)*-1.00);
		teSalary.setAbsenceSalary(Double.parseDouble(absenceSalary)*-1.00);
		teSalary.setWuxianyijin(Double.parseDouble(wuxianyijin)*-1.00);
		teSalary.setOvertimeSalary(Double.parseDouble(overtimeSalary));
		teSalary.setBonusSalary(Double.parseDouble(bonusSalary));
		
		teSalary.setEmployeesId(emId);
		teSalary.setSalaryTime(DateTimeUtil.conversionTime(DateTimeUtil.getCurrentTime(), "yyyy-MM"));
		
		salaryDao.save(teSalary);
		
		
		return JSONReturn.buildSuccess("添加成功!");
	}

	@Transactional
	public JSONReturn modifySalarySalary(long id, long emId, String baseSalary, String lateSalary, String absenceSalary,
			String wuxianyijin, String overtimeSalary, String bonusSalary, String acctName) {
		
		// TODO Auto-generated method stub
		if (StringUtils.isEmpty(baseSalary) || StringUtils.isEmpty(lateSalary) || StringUtils.isEmpty(absenceSalary) || StringUtils.isEmpty(wuxianyijin) || StringUtils.isEmpty(overtimeSalary) || StringUtils.isEmpty(bonusSalary))
			return JSONReturn.buildFailure("添加失败!");
		/*TeAccount account = accountDao.findUniqueByProperty(TeAccountField.ACCT_NAME, user);
		if (CompareUtil.isNotEmpty(account))
			return JSONReturn.buildFailure("添加失败, 用户名重复!");*/
		
		TeSalary teSalary =  salaryDao.findUniqueByProperty(TeSalaryField.SALARY_ID, id);;
		teSalary.setSalaryId(id);
		teSalary.setBaseSalary(Double.parseDouble(baseSalary));
		teSalary.setLateSalary(Double.parseDouble(lateSalary));
		teSalary.setAbsenceSalary(Double.parseDouble(absenceSalary));
		teSalary.setWuxianyijin(Double.parseDouble(wuxianyijin));
		teSalary.setOvertimeSalary(Double.parseDouble(overtimeSalary));
		teSalary.setBonusSalary(Double.parseDouble(bonusSalary));
		teSalary.setEmployeesId(emId);
		
		return JSONReturn.buildSuccess("修改成功!");
	}


	public JSONReturn findSalaryById(long id) {
		TeSalary teSalary = salaryDao.findById(id);
		TeEmployeesBasic emDto = employeesBasicDao.findById(teSalary.getEmployeesId());
		String emDep = null;
		if (emDto.getEmDeparemtn() > 0) {
			TeDepartment department = departmentDao.findUniqueByProperty(TeDepartmentField.DEPT_ID, emDto.getEmDeparemtn());
			emDep = department.getDeptName();
		}
		
		if (CompareUtil.isEmpty(teSalary))
			return JSONReturn.buildFailure("操作失败, 源数据不存在");
		return JSONReturn.buildSuccess(new SalaryInfoDto(teSalary.getSalaryId(), emDto.getEmFullName(), teSalary.getEmployeesId(),
				emDto.getEmSex(), emDep, teSalary.getBaseSalary(), teSalary.getLateSalary(), teSalary.getAbsenceSalary(),
				teSalary.getWuxianyijin(), teSalary.getOvertimeSalary(), teSalary.getBonusSalary(), teSalary.getSalaryTime()));
		
	}
	
	public SalaryInfoDto findSalaryInfoDtoById(long id) {
		TeSalary teSalary = salaryDao.findById(id);
		TeEmployeesBasic emDto = employeesBasicDao.findById(teSalary.getEmployeesId());
		String emDep = null;
		if (emDto.getEmDeparemtn() > 0) {
			TeDepartment department = departmentDao.findUniqueByProperty(TeDepartmentField.DEPT_ID, emDto.getEmDeparemtn());
			emDep = department.getDeptName();
		}
		
		if (CompareUtil.isEmpty(teSalary))
			return null;
		return new SalaryInfoDto(teSalary.getSalaryId(), emDto.getEmFullName(), teSalary.getEmployeesId(),
				emDep, teSalary.getBaseSalary(), teSalary.getLateSalary(), teSalary.getAbsenceSalary(),
				teSalary.getWuxianyijin(), teSalary.getOvertimeSalary(), teSalary.getBonusSalary(), teSalary.getSalaryTime());
		
	}


	/**
	 * 导出到E盘
	 */
	public JSONReturn exportExcelSalaryById(long id) {
		
		SalaryInfoDto salary = findSalaryInfoDtoById(id);
		
		List<SalaryInfoDto> salaryList = new ArrayList<SalaryInfoDto>();
		salaryList.add(salary);
		
		
		PoiExcelExport pee = new PoiExcelExport("E:/员工薪酬工资单.xls","sheet1");  
		
		
		// 调用
		String titleColumn[] = { "id", "employeesName", "emId", "deparemtn", "baseSalary", "lateSalary", "absenceSalary", "wuxianyijin", "overtimeSalary", "bonusSalary", "salaryTime", ""};
		String titleName[] = { "ID号", "姓名", "编号", "所属部门", "基本工资", "迟到", "缺勤", "五险一金", "加班费", "奖金", "工资月份", "实发工资"};
		int titleSize[] = { 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13};
		// 其他设置 set方法可全不调用
		String colFormula[] = new String[12];
		colFormula[11] = "E@+F@+G@+H@+I@+J@";   //设置第13列实发工资的公式
		pee.setColFormula(colFormula);
		

		pee.wirteExcel(titleColumn, titleName, titleSize, salaryList);

		return JSONReturn.buildSuccess("导出成功!");
	}
	/**
	 * 通过浏览器下载导出
	 */
	public void testexportExcelSalaryById(long id, HttpServletResponse response) {
		
		SalaryInfoDto salary = findSalaryInfoDtoById(id);
		
		List<SalaryInfoDto> salaryList = new ArrayList<SalaryInfoDto>();
		salaryList.add(salary);
		PoiExcelExport pee = new PoiExcelExport(response, salary.getEmployeesName()+salary.getSalaryTime()+"工资单","sheet1");  
		// 调用
		String titleColumn[] = { "id", "employeesName", "emId", "deparemtn", "baseSalary", "lateSalary", "absenceSalary", "wuxianyijin", "overtimeSalary", "bonusSalary", "salaryTime", ""};
		String titleName[] = { "ID号", "姓名", "编号", "所属部门", "基本工资", "迟到", "缺勤", "五险一金", "加班费", "奖金", "工资月份", "实发工资"};
		int titleSize[] = { 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13};
		// 其他设置 set方法可全不调用
		String colFormula[] = new String[12];
		colFormula[11] = "E@+F@+G@+H@+I@+J@";   //设置第13列实发工资的公式
		pee.setColFormula(colFormula);
		pee.wirteExcel(titleColumn, titleName, titleSize, salaryList);

		
	}

	/**
	 * 导出所有员工数据
	 */
	public void exportAllExcelSalary(HttpServletResponse response , String salaryMonth) {
		

		if(salaryMonth == "NoSalaryMonth" || salaryMonth == ""){
			salaryMonth = DateTimeUtil.conversionTime(DateTimeUtil.getCurrentTime(), "yyyy-MM");
		}
		
		List<SalaryInfoDto> salaryList = findAllSalaryListByTime(salaryMonth);
		
		PoiExcelExport pee = new PoiExcelExport(response, "所有员工" + salaryMonth +"工资单","sheet1");  
		// 调用
		String titleColumn[] = { "id", "employeesName", "emId", "deparemtn", "baseSalary", "lateSalary", "absenceSalary", "wuxianyijin", "overtimeSalary", "bonusSalary", "salaryTime", ""};
		String titleName[] = { "ID号", "姓名", "编号", "所属部门", "基本工资", "迟到", "缺勤", "五险一金", "加班费", "奖金", "工资月份", "实发工资"};
		int titleSize[] = { 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13};
		// 其他设置 set方法可全不调用
		String colFormula[] = new String[12];
		colFormula[11] = "E@+F@+G@+H@+I@+J@";   //设置第13列实发工资的公式
		pee.setColFormula(colFormula);
		pee.wirteExcel(titleColumn, titleName, titleSize, salaryList);
		
	}

}
